<?php

/**
 *
 * @license   https://www.rongyun.cc
 * @link      https://www.rongyun.cc
 * @author    wangyadong<wangyadong280@gmail.com>
 * @date      2017-05-11 17:53
 */

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Auth;
use App\Transformers\UserTransformer;
use Fractal;

class AuthController extends BaseController
{
    protected $guard = 'api';


    public function token(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->errorBadRequest($validator);
        }

        $credentials = $request->only('name', 'password');

        try {
            if (!$token = Auth::guard($this->guard)->attempt($credentials)) {
               return response()->json(['errors' => '用户名和密码错误'], 401);
            }
        } catch (JWTException $e) {
            return response()->json(['errors' => '用户异常'], 500);
        }

        return response()->json(compact('token'));
    }

    /**
     * 获取用户信息
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function User()
    {
        $useritem = Fractal::item(Auth::user(), new UserTransformer())->getArray();
        return $this->apiResponse($useritem, '获取用户信息成功');
    }
}